$('document').ready(function(){
    var decalage = 20;
    var nbBout;   
    var Qmax = 3;
    var Qnumber = 1;
    var reponses = {}; // Réponses de l'utilisateur

    loadDisplay(null);

    function setCountDown(){
        $('#countdown_image').addClass('alert_image1');
        $('#countdown').countDown({
            startNumber: 15,
            endNumber: 0,
            startFontSize: '36px',
            endFontSize: '20px',
            callBack: function(me) {
                saveResponse();
                if(Qnumber < Qmax){
                    requestNewQuestion();
                }
                if(Qnumber == Qmax){
                   endGame();
                }
                Qnumber++;
                updateNav();
            },
            callEach: function(me) {
                var value = $('#countdown').html();
                switch(value){
                    case "14" :
                        $('#countdown_image').addClass('alert_image1');
                        $('#countdown_image').removeClass('alert_image3');
                        break;
                    case "10" :
                        $('#countdown_image').toggleClass('alert_image2 alert_image1');
                        break;
                    case "5" :
                        $('#countdown_image').toggleClass('alert_image2 alert_image3');
                        break;
                    case "0" :
                        $('#countdown_image').toggleClass('alert_image1 alert_image3');
                        break;
                }                    
            }
        });
    }
    
    function updateNav(position){
        if(!position)
            position = Qnumber;
        var last_pos = position-1;

        if(last_pos != 0)
            $('#nav' + last_pos).toggleClass('nav_active nav');
        $('#nav' + position).toggleClass('nav_active nav');
 
    }
    
    function saveResponse(){
        

        var param = "&qtype="+$('#qtype').html();
        
        //console.log($('#menu ul').children());
        
        $('#menu ul').children().each(function(){
            if($(this).attr('id').match(/^result/)){
                var response_fid = $(this).find('span.response_fid').html();
                var fid = $(this).find('span.fid').html();
                var response  = $(this).find('span.response').html();

                var correct = 0;
                if(response_fid == fid)
                    correct = 1;

                param += '&' + response_fid + '='+response + '_' + correct;
            }
        });
        
        $.ajax({
            type:"POST",
            url:'pages/ajax.php',
            data: 'action=saveResponse'+param,
            success : function(response){
                var object = $.parseJSON(response);
                //console.log(object);
            }
        });   
    }
        
    function cercle(nb, div, centre){
        var angle = 360 / nb;      
        nbBout = nb;
        var posX,posY;
        var rayon = 160;
        var centreX = document.getElementById(centre).offsetLeft;
        var centreY = document.getElementById(centre).offsetTop;
        var lItem = 20;
        var i = 1;
        var item;
        var b = 0;
        $('#menu ul').children().each(function(){
            posX = centreX + 20 + rayon * Math.cos((b + decalage) * Math.PI / 180);
            posY = centreY - 20 + rayon * Math.sin((b + decalage) * Math.PI / 180); 
 
            var id = $(this).attr('id');
            $('#'+id).addClass("item");  
            
            if($(this).attr('id').match(/^item/)){
                var num = $(this).attr('id').substr(-1, 1);
                var fid = $('#user' + num).html();
                $('#'+id).addClass("photo");  
                this.fid = fid;
            }
            if($(this).attr('id').match(/^result/)){
                $('#'+id).addClass("cercle_reponse");  
            }
            
            this.style.top = (posY - lItem / 2) + "px"; 
            this.style.left = (posX - lItem / 2) + "px";
            this.initX = (posX - lItem / 2);
            this.initY = (posY - lItem / 2);
        
            b+= angle;
        });
        
       
    }
    function setDrag(nb,id){
        for ( var i=1; i<=nb; i++ ) {
            $('#item'+i).draggable({
                revert : true
            });
            $('#result'+i).droppable({
                drop : handleDrop
            });
        }                    
    }
    function handleDrop(event, ui) {
        var fid = ui.draggable[0].fid;
        ui.draggable.position( {
            of: $(this), 
            my: 'center', 
            at: 'center'
        } );
        var friendId = $(this).find('span.fid').html();
        $(this).find('span.response_fid').html(fid);

        ui.draggable.draggable( 'option', 'revert', 'invalid' );
        $(this).css('background-image', 'url("/themes/img/cercle2.png")');
    }  
    
    // Charge les cercles
    function loadDisplay(type){                     
        if(type == null)
            type= $('#qtype').html();
        $("#container").empty().html('<div id="loading"> <img src="themes/img/loading.gif" /> </div>');        
        
        var url = 'pages/display.php';
        $('#container').load(url,{
            qtype : type
        }, function(e,response) {
            if(response == 'success'){
                var len =  $('#menu ul').children().length;
                cercle(len, 'item', "centre");
                //                cercle(len, 'response', "centre3");
                setDrag(len,'item');
                setCountDown();
            }
            
        });
    }
    
    // Charge une nouvelle question
    function requestNewQuestion(){
        $.ajax({
            type:"POST",
            url:'pages/ajax.php',
            data: 'action=getQuestion',
            success : function(response){
                var object = $.parseJSON(response);
                //console.log(object);
                $('#qtype').html(object.type_id);
                $('#question').html(object.question);                
                loadDisplay(object.type_id);  
            }
        });        
    }


    function endGame(){
       $('#menu').hide();
       $('#barre').hide();
       $('#countdown').hide();
       $('#navigation').hide();
       $('#navigation').hide();
       $('#countdown_image').hide();
       
       url = 'pages/score.php';
       $('#container').load(url);
    }

});


function postToFeed(score) {
    FB.init({appId: "289694684387998", status: true, cookie: true, frictionlessRequests : true});
    var obj = {
      method: 'feed',
      link: 'https://apps.facebook.com/friendsplus_/',
      name: 'FriendsPlus',
      caption: 'Connais-tu ton ami ?',
      description: "J'ai obtenu un score de " + score
    };
    
    console.log(obj);

    function callback(response) {
      document.getElementById('msg').innerHTML = "Post ID: " + response['post_id'];
    }

    FB.ui(obj, callback);
  }
  
function shareApp(){
   FB.init({appId: "289694684387998", status: true, cookie: true, frictionlessRequests : true});
   FB.ui({
      method: 'send',
      name: 'FriendsPlus',
      picture: 'http://dev.fb/themes/img/logo_achivement.png',
      description: 'FriendsPlus est un quizz qui te permet de savoir si tu connais réellement tes amis !',
      link: 'https://apps.facebook.com/friendsplus_/'
      });
}

function sendRequestViaMultiFriendSelector() {
  FB.init({appId: "289694684387998", status: true, cookie: true, frictionlessRequests : true});  
  FB.ui({method: 'apprequests',
    message: 'Invite tes amis à jouer aussi afin de voir si ils connaissent leurs amis autant que toi !'
  }, requestCallback);
  
    function requestCallback(response) {
    // Handle callback here
    console.log(response);
  }
}
